﻿CREATE PROCEDURE [acms].[TemplateHierarchy_Put]
	@Id int, 
	@ParentId int, 
	@ChildId int, 
	@Sequence int, 
	@ConcurencyId rowversion, 
	@IdOut int output, 
	@ParentNameOut varchar(255) output, 
	@ChildNameOut varchar(255) output, 
	@SequenceOut int output, 
	@ConcurencyIdOut rowversion output
AS

	if(@Sequence = null or @Sequence = -1)
		select @Sequence = isnull(Max(Sequence) + 1, 0) from TemplateHierarchy where ParentId = @ParentId
	
	if (@Id is null or @Id = 0) begin
		insert into TemplateHierarchy
			(ParentId, ChildId, [Sequence])
		values
			(@ParentId, @ChildId, @Sequence)
		set @IdOut = @@identity
	end
	else begin
		update TemplateHierarchy
		set ParentId = @ParentId,
			ChildId = @ChildId,
			[Sequence] = @Sequence
		where
			Id = @Id and ConcurencyId = @ConcurencyId
		
		if(@@rowcount = 1) begin
			set @IdOut= @Id
		end
		else begin
			if exists(select null from TemplateHierarchy where Id = @Id)
				return -100
			else
				return -200
		end
	end
	
	select @ParentNameOut = ParentName, @ChildNameOut = ChildName, @SequenceOut = [Sequence], @ConcurencyIdOut = ConcurencyId 
	from TemplateHierarchy_View 
	where Id = @IdOut
	
RETURN 0;